package kernel

import (
	"encoding/json"
	"fmt"
	"os"
	"time"
)

var (
	Conf = &Config{}
)

// 从文件中加载配置到viper
func Load(file string) (conf *Config, err error) {
	if file == "" {
		var wd string
		wd, err = os.Getwd()
		if err != nil {
			return
		}
		file = wd + "/config.json"
	}
	// 读取文件
	var data []byte
	data, err = os.ReadFile(file)
	if err != nil {
		return
	}

	// 将 JSON 数据解析到结构体中
	err = json.Unmarshal(data, &conf)
	if err != nil {
		return
	}
	return
}

type Config struct {
	Bind                string        `mapstructure:"bind" json:"bind"`
	Port                int           `mapstructure:"port" json:"port"`
	ReadHeaderTimeout   time.Duration `mapstructure:"read-header-timeout" json:"read-header-timeout"`
	WriteTimeout        time.Duration `mapstructure:"write-timeout" json:"write-timeout"`
	MaxHeaderBytes      int           `mapstructure:"max-header-bytes" json:"max-header-bytes"`
	ForwardedByClientIP bool          `mapstructure:"forwarded-by-client-ip" json:"forwarded-by-client-ip"`
	TrustedProxies      []string      `mapstructure:"trusted-proxies" json:"trusted-proxies"`
	JWT                 *JwtConfig    `mapstructure:"jwt" json:"jwt"`
	Log                 *LogConfig    `mapstructure:"log" json:"log"`
	MySQL               *MySQL        `mapstructure:"mysql" json:"mysql"`
}

func (conf *Config) Addr() string {
	return fmt.Sprintf("%s:%d", conf.Bind, conf.Port)
}
